<template>
  <plain-page>
    <el-row :gutter="8" class="section">
      <el-col :span="6">
        <el-popover
          placement="top-end"
          trigger="hover"
          :open-delay="0"
          :close-delay="0"
        >
          <div>
            <el-button type="text" @click="onUserStatClick">查看用户数据统计</el-button>
            <el-button type="text" @click="onOrgUserStatClick">社区用户数据汇总</el-button>
          </div>
          <total-card
            slot="reference"
            :icon="icons.user"
            :title="userCardTitle"
            :number="totals.user"
            @click.native="onTotalCardClick('user')"
          />
        </el-popover>
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.user"
          title="留守老人"
          :number="totals.leftBehindElderly"
          @click.native="onTotalCardClick('leftBehindElderly')"
        />
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.street"
          title="街道"
          :number="totals.street"
          @click.native="onTotalCardClick('street')"
        />
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.org"
          title="社区"
          :number="totals.org"
          @click.native="onTotalCardClick('org')"
        />
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.yanglaoyuan"
          title="养老机构"
          :number="totals.yanglaoyuan"
          @click.native="onTotalCardClick('yanglaoyuan')"
        />
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.volunteer"
          title="志愿者"
          :number="totals.volunteer"
          @click.native="onTotalCardClick('volunteer')"
        />
      </el-col>
      <el-col :span="3">
        <total-card
          :icon="icons.service"
          title="服务机构"
          :number="totals.provider"
          @click.native="onTotalCardClick('provider')"
        />
      </el-col>
    </el-row>
    <el-row :gutter="8" class="section">
      <el-col :span="6">
        <chart-stat-card
          title="今日销售额"
          :number="today.tradeMoney"
          unitText="元"
          :precision="2"
          class="today-trade-amount"
          @click.native="onChartStatCardClick('tradeMoney')"
        />
      </el-col>
      <el-col :span="6">
        <chart-stat-card
          title="今日交易数"
          :number="today.tradeTimes"
          unitText="次"
          class="today-trade-times"
          @click.native="onChartStatCardClick('tradeTimes')"
        />
      </el-col>
      <el-col :span="6">
        <chart-stat-card
          title="当月订单数"
          :number="orders"
          unitText="单"
          class="this-month-orders"
          @click.native="onChartStatCardClick('orders')"
        />
      </el-col>
      <el-col :span="6">
        <chart-stat-card
          title="老年卡交易数"
          :number="oldcardTradeTimes"
          unitText="次"
          class="old-card-trade-times"
          @click.native="onChartStatCardClick('oldcardTradeTimes')"
        />
      </el-col>
    </el-row>
    <div style="height: calc(100% - 230px);">
      <div style="height: 50%;margin-top: 8px">
        <transition name="el-zoom-in-top" appear>
          <trade-chart-card
            ref="tradeChartCard"
            dashboard
            :visible="isCurrent"
            class="chart-card"
            @query="onTradeQuery"
            @click.native="onChartCardClick('trade')" />
        </transition>
      </div>
      <div style="height: 50%;margin-top: 10px">
        <transition name="el-zoom-in-top" appear>
          <order-chart-card
            ref="orderChartCard"
            dashboard
            :visible="isCurrent"
            class="chart-card"
            @query="onOrderQuery"
            @click.native="onChartCardClick('order')" />
        </transition>
      </div>
    </div>
    <!--
    <el-card v-if="app.admin.roleId == 1" shadow="hover" class="section">
      <div slot="header">近7天日活跃终端用户数</div>
      <app-dau />
    </el-card>-->
  </plain-page>
</template>

<script>
import TotalCard from './TotalCard';
import ChartStatCard from './ChartStatCard';
import TradeChartCard from '@/pages/shop/stat/TradeChartCard';
import OrderChartCard from '@/pages/shop/stat/OrderChartCard';
import moment from 'moment';

// 图片
import org from './totalcard-imgs/org.png';
import user from './totalcard-imgs/user.png';
import street from './totalcard-imgs/street.png';
import service from './totalcard-imgs/service.png';
import volunteer from './totalcard-imgs/volunteer.png';
import yanglaoyuan from './totalcard-imgs/yanglaoyuan.png';

const TODAY = moment().format('MM-DD');
const ONE_MINUTE = 1000 * 60;

export default {
  pageProps: {
    title: '首页'
  },
  components: {
    TotalCard,
    ChartStatCard,
    TradeChartCard,
    OrderChartCard,
    //...(app.admin.roleId == 1 ? {'app-dau': () => import('./AppDAU')} : {})
  },
  computed: {
    userCardTitle() {
      return app.admin.orgId == 94 ? '户籍老年人口' : '用户';
    }
  },
  data() {
    this.icons = {
      org, user, street, service, volunteer, yanglaoyuan
    };
    this.moment = moment;

    return {
      totals: {
        user: 0,
        leftBehindElderly: 0,
        street: 0,
        org: 0,
        yanglaoyuan: 0,
        volunteer: 0,
        provider: 0
      },
      today: {
        tradeMoney: 0,
        tradeTimes: 0,
      },
      orders: 0,
      oldcardTradeTimes: 0
    };
  },
  mounted() {
    this.queryUpdateAll();
    this.startTimer();
  },
  destroyed() {
    this.stopTimer();
  },
  methods: {
    onTradeQuery(data) {
      let last = data[data.length - 1];
      if (last.statDate == TODAY) {
        this.today.tradeMoney = last.income;
        this.today.tradeTimes = last.tradeAmount;
      }
    },
    onOrderQuery(data) {
      this.orders = data.reduce((sum, item) => sum + item.ordersQuantity, 0);
    },
    onTotalCardClick(code) {
      if (!this.checkHasAuth({
        user: "/smart_info_center/life/user/user",
        leftBehindElderly: "/smart_info_center/life/user/user",
        street: "/system/org",
        org: "/system/org",
        volunteer: "/smart_info_center/life/volunteer/volunteer",
        provider: "/pension_service_center/provider/shop",
        yanglaoyuan: "/intelligent_sunshine_management/service/resthome"
      }[code])) return;
      switch (code) {
      case 'user':
        this.pushPage({
          path: '/user',
          params: {
            query: {}
          }
        });
        break;
      case 'leftBehindElderly':
        this.pushPage({
          path: '/user',
          params: {
            query: {
              specialTypes: ['20']
            }
          }
        });
        break;
      case 'yanglaoyuan':
        this.pushPage('/resthome');
        break;
      case 'volunteer':
        this.pushPage('/volunteer/volunteer');
        break;
      case 'org':
        this.openTab({
          title: '组织管理',
          url: 'org/orgGrid.do'
        });
        break;
      case 'street':
        this.openTab({
          title: '组织管理',
          url: 'org/orgGrid.do'
        });
        break;
      case 'provider':
        this.pushPage('/shop/shop');
        break;
      }
    },
    onChartStatCardClick(type) {
      if (!this.checkHasAuth({
        tradeMoney: '/pension_service_center/provider/shop.financeManager',
        tradeTimes: '/pension_service_center/provider/shop.financeManager',
        orders: '/pension_service_center/supervise/service_personnel_management/order',
        oldcardTradeTimes: '/pension_service_center/provider/shop.financeManager'
      }[type])) return;
      switch(type) {
        case 'tradeMoney':
        case 'tradeTimes':
          this.pushPage({
            path: '/shop/finance/trade',
            params: {
              query: {
                createTimes: [
                  moment().format('YYYY-MM-DD 00:00:00'),
                  moment().format('YYYY-MM-DD 23:59:59')
                ]
              }
            }
          });
          break;
        case 'orders':
          this.pushPage({
            path: '/shop/order/service',
            params: {
              query: {
                createTimes: [
                  moment().format('YYYY-MM-01 00:00:00'),
                  moment().format('YYYY-MM-DD 23:59:59')
                ]
              }
            }
          });
          break;
        case 'oldcardTradeTimes':
          this.pushPage({
            path: '/shop/finance/trade',
            params: {query: {yhType: -2}}
          });
          break;
      }
    },
    onChartCardClick(type) {
      if (!this.checkHasAuth({
        trade: '/datastat/shop.stat/shop.stat.trade',
        order: '/datastat/shop.stat/shop.stat.order',
      }[type])) return;
      switch (type) {
        case 'trade':
          this.pushPage('/shop/stat/trade');
          break;
        case 'order':
          this.pushPage('/shop/stat/order');
          break;
      }
    },
    onOrgUserStatClick() {
      this.pushPage('/stat/org-user-stat');
    },
    onUserStatClick() {
      this.pushPage('/stat/user-stat');
    },
    checkHasAuth(permission) {
      if (this.$auth(permission)) {
        return true;
      } else {
        this.$message.warning('没有查看权限');
        return false;
      }
    },
    updateTotalCount() {
      const ret = this.$http.get('/api/datastat/numberInMap').then(ret => {
        if (app.admin.orgId == 94) {
          ret.user = 57080;
          ret.org = 144;
        }
        Object.assign(this.totals, ret);
      });
    },
    updateOldcardTradeTimes() {
      this.$http.get('/api/shop/stat/countOldcardTradeTimes').then(ret => {
        this.oldcardTradeTimes = ret;
      });
    },
    startTimer() {
      this.timers = [
        setInterval(this.updateTotalCount.bind(this), 1 * ONE_MINUTE),
        setInterval(this.updateOldcardTradeTimes.bind(this), 10 * ONE_MINUTE),
        setInterval(() => { this.$refs.tradeChartCard.dashboardRefresh(); }, 5 * ONE_MINUTE),
        setInterval(() => { this.$refs.orderChartCard.dashboardRefresh(); }, 5 * ONE_MINUTE)
      ];
    },
    stopTimer() {
      this.timers.forEach(timer => {
        clearInterval(timer);
      });
    },
    queryUpdateAll() {
      this.updateTotalCount();
      this.updateOldcardTradeTimes();
      this.$refs.tradeChartCard.dashboardRefresh();
      this.$refs.orderChartCard.dashboardRefresh();
    },
    onPageResume() {
      this.onShow();
    },
    onPagePause() {
      this.onHide();
    },
    onShow() {
      this.startTimer();
      this.queryUpdateAll();
    },
    onHide() {
      this.stopTimer();
    }
  }
}
</script>

<style scoped>
.plain-page {
  min-width: 1002px;
  min-height: 612px !important;
  height: calc(100% - 17px);
  padding: 0px 5px;
}
.section {
  margin-top: 8px;
}
h1 {
  color: #606266;
}
.chart-card {
  height: 100%;
}

.chart-stat-card.today-trade-amount >>> .number,
.chart-stat-card.today-trade-times >>> .number,
.chart-stat-card.this-month-orders >>> .number,
.chart-stat-card.old-card-trade-times >>> .number {
  transition: .2s color ease;
}
.chart-stat-card.today-trade-amount:hover >>> .number {
  color: #FF005A;
}
.chart-stat-card.today-trade-times:hover >>> .number {
  color: #3888fa;
}
.chart-stat-card.this-month-orders:hover >>> .number {
  color: #67c23a;
}
.chart-stat-card.old-card-trade-times:hover >>> .number {
  color: #ffb980;
}
</style>
<style>
.user-total-card-popover {
  padding: 0;
  text-align: center;
}
</style>